package com.kd.juhaowan.utils;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import android.text.format.Formatter;

import java.util.List;

/**
 * Created by Administrator on 2017/6/2 0002.
 */

public final class DeviceUtil {

    private static final String TAG = DeviceUtil.class.getSimpleName();

    private DeviceUtil() {
    }

    /**
     * 获取手机内存大小
     *
     * @param context 上下文
     * @return
     */
    public static String getTotalMemory(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        return Formatter.formatFileSize(context, mi.totalMem);
    }

    /**
     * 获取当前可用内存大小s
     *
     * @param context
     * @return
     */
    public static String getAvailMemory(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        return Formatter.formatFileSize(context, mi.availMem);
    }


    public static boolean isVersionNewer(String oldVersion, String newVersion) {
        String[] oldVersionParts = oldVersion.split("\\.");
        String[] newVersionParts = newVersion.split("\\.");

        int length = Math.max(oldVersionParts.length, newVersionParts.length);

        for (int i = 0; i < length; i++) {
            int oldPart = i < oldVersionParts.length ? Integer.parseInt(oldVersionParts[i]) : 0;
            int newPart = i < newVersionParts.length ? Integer.parseInt(newVersionParts[i]) : 0;

            if (oldPart < newPart) {
                return true; // 新版本号更新
            } else if (oldPart > newPart) {
                return false; // 旧版本号更新
            }
        }

        return false; // 版本号相同
    }

//    /**
//     * CPU最大频率
//     *
//     * @return
//     */
//    public static String getMaxCpuFreq() {
//        return readFileContent("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq") + "Hz";
//    }
//
//    // 获取CPU最小频率（单位KHZ）
//    public static String getMinCpuFreq() {
//        return readFileContent("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq") + "Hz";
//    }
//
//    /**
//     * 实时获取CPU当前频率（单位KHZ）
//     *
//     * @return
//     */
//    public static String getCurCpuFreq() {
//        return readFileContent("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq") + "Hz";
//    }

//    //CPU名字
//    public static String getCpuName() {
//        InputStreamReader fileReader = null;
//        FileInputStream fileStream = null;
//        BufferedReader bufferedReader = null;
//        try {
//            fileStream = new FileInputStream("/proc/cpuinfo");
//            fileReader = new InputStreamReader(fileStream, "utf-8");
//            bufferedReader = new BufferedReader(fileReader);
//            String text = bufferedReader.readLine();
//            String[] array = text != null ? text.split(":\\s+", 2) : new String[0];
//            return array.length >= 1 ? array[1] : "unkown";
//        } catch (UnsupportedEncodingException e) {
//            WL.e(TAG, "getCpuName ---> UnsupportedEncodingException");
//        } catch (FileNotFoundException e) {
//            WL.e(TAG, "getCpuName ---> FileNotFoundException");
//        } catch (IOException e) {
//            WL.e(TAG, "getCpuName ---> IOException");
//        } finally {
//            IoUtils.closeSilently(bufferedReader);
//            IoUtils.closeSilently(fileReader);
//            IoUtils.closeSilently(fileStream);
//        }
//        return "unkown";
//    }

    public static boolean isInstallApp(Context context,String packagename){
//        boolean isInstalled = false;
//        List<PackageInfo> packages = context.getPackageManager().getInstalledPackages(0);
//        if(packages != null){
//            for (PackageInfo i : packages) {
////                    LogUtil.debugLog(i.packageName+"..."+packagename);
//                    if(i.packageName.equals(packagename)){
//                        isInstalled = true;
//                        break;
//                    }
//
//                }
//            }
//
//
//     return isInstalled;
        PackageManager packageManager = context.getPackageManager();
        try {
            packageManager.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }
    /**
     * 获取手机安装的应用信息（排除系统自带）
     *
     * @param context
     * @return
     */
    public static String getAllApp(Context context) {
        StringBuilder result = new StringBuilder();
        List<PackageInfo> packages = context.getPackageManager().getInstalledPackages(0);
        if(packages != null){
            for (PackageInfo i : packages) {
                if ((i.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {

                    result.append(i.applicationInfo.loadLabel(context.getPackageManager()).toString());
                    result.append(",");
                }
            }
        }

        String resultStr = result.toString();

        if (TextUtils.isEmpty(resultStr)) {
            return "null";
        } else {
            return resultStr.substring(0, Math.max(resultStr.length() - 1, 0));
        }
    }

//    /**
//     * 是否安装了微信
//     * @param context
//     * @return
//     */
//    public static boolean isInstalledWeChat(Context context) {
//        WL.d(TAG, "isInstalledWeChat ------->");
//        PackageManager pm = context.getPackageManager();
//        List<PackageInfo> packages = pm.getInstalledPackages(0);
//        for (PackageInfo info : packages) {
//            if ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
//                if (TextUtils.equals("com.tencent.mm", info.applicationInfo.packageName)) {
//                    return true;
//                } else if (TextUtils.equals("com.tencent.mm", info.applicationInfo.processName)) {
//                    return true;
//                } else {
//                    String appName = info.applicationInfo.loadLabel(pm).toString().toLowerCase();
//                    if (TextUtils.equals(appName, "wechat") || TextUtils.equals(appName, "微信")) {
//                        return true;
//                    }
//                }
//            }
//        }
//        return false;
//    }
//
//    /**
//     * 是否安装了云闪付APP
//     * @param context
//     * @return
//     */
//    public static boolean isInstalledUnionPay(Context context){
//        WL.d(TAG, "isInstalledUnionPay ------->");
//        PackageManager pm = context.getPackageManager();
//        List<PackageInfo> packages = pm.getInstalledPackages(0);
//        for (PackageInfo info : packages) {
//            if ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
//                if (TextUtils.equals("com.unionpay", info.applicationInfo.packageName)) {
//                    return true;
//                } else if (TextUtils.equals("com.unionpay", info.applicationInfo.processName)) {
//                    return true;
//                } else {
//                    String appName = info.applicationInfo.loadLabel(pm).toString().toLowerCase();
//                    if (TextUtils.equals(appName, "云闪付")) {
//                        return true;
//                    }
//                }
//            }
//        }
//        return false;
//    }
//
//    /**
//     * 获取手机MAC地址
//     *
//     * @param context
//     * @return
//     */
//    public static String getMacAddress(Context context) {
////        String macAddress = null;
////        Context applicationContext = context.getApplicationContext();
////        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
////            WifiManager wifiMgr = (WifiManager)applicationContext.getSystemService(Context.WIFI_SERVICE);
////            WifiInfo info = (null == wifiMgr ? null : wifiMgr.getConnectionInfo());
////            if (null != info) {
////                macAddress = info.getMacAddress();
////            }
////        }
////
////        if(!TextUtils.isEmpty(macAddress)){
////            return macAddress;
////        }
////
////        StringBuffer buf = new StringBuffer();
////        NetworkInterface networkInterface = null;
////        try {
////            networkInterface = NetworkInterface.getByName("eth1");
////            if (networkInterface == null) {
////                networkInterface = NetworkInterface.getByName("wlan0");
////            }
////            if (networkInterface == null) {
////                return "02:00:00:00:00:00";
////            }
////            byte[] addr = networkInterface.getHardwareAddress();
////
////            if(addr == null){
////                return "02:00:00:00:00:00";
////            }
////
////            for (byte b : addr) {
////                buf.append(String.format("%02X:", b));
////            }
////
////            if (buf.length() > 0) {
////                buf.deleteCharAt(buf.length() - 1);
////            }
////            macAddress = buf.toString();
////        } catch (SocketException e) {
////            e.printStackTrace();
////            macAddress = "02:00:00:00:00:00";
////        }
////        return macAddress;
//        String mac = getMac1(context);
//        if (!TextUtils.isEmpty(mac)) {
//            return mac;
//        }
//        mac = getMac2();
//        if (!TextUtils.isEmpty(mac)) {
//            return mac;
//        }
//        mac = getMac3();
//        if (!TextUtils.isEmpty(mac)) {
//            return mac;
//        }
//        mac = getMac4();
//        if (!TextUtils.isEmpty(mac)) {
//            return mac;
//        }
//        return "02:00:00:00:00:00";
//    }
//
//    private static String getMac1(Context ctx) {
//        WifiManager wifi = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
//        WifiInfo info = wifi.getConnectionInfo();
//        if (info != null) {
//            return "02:00:00:00:00:00".equals(info.getMacAddress())?"":info.getMacAddress();
//        }
//        return null;
//    }
//
//    public static String getMac2() {
//        String macSerial = null;
//        String str = "";
//        try {
//            Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address ");
//            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
//            LineNumberReader input = new LineNumberReader(ir);
//            for (; null != str;) {
//                str = input.readLine();
//                if (str != null) {
//                    macSerial = str.trim();// 去空格
//                    break;
//                }
//            }
//        } catch (IOException ex) {
//            // 赋予默认值
//            ex.printStackTrace();
//        }
//        return "02:00:00:00:00:00".equals(macSerial)?"":macSerial;
//    }
//
//    /**
//     * 根据IP地址获取MAC地址
//     *
//     * @return
//     */
//    public static String getMac3() {
//        String strMacAddr = null;
//        try {
//            // 获得IpD地址
//            InetAddress ip = getLocalInetAddress();
//            byte[] b = NetworkInterface.getByInetAddress(ip).getHardwareAddress();
//            StringBuffer buffer = new StringBuffer();
//            for (int i = 0; i < b.length; i++) {
//                if (i != 0) {
//                    buffer.append(':');
//                }
//                String str = Integer.toHexString(b[i] & 0xFF);
//                buffer.append(str.length() == 1 ? 0 + str : str);
//            }
//            strMacAddr = buffer.toString().toUpperCase();
//        } catch (Exception e) {
//            Log.e("51wan","error"+e.getMessage());
//            e.printStackTrace();
//        }
//
//        return "02:00:00:00:00:00".equals(strMacAddr)?"":strMacAddr;
//    }
//
//    /**
//     * 获取移动设备本地IP
//     *
//     * @return
//     */
//    private static InetAddress getLocalInetAddress() {
//        InetAddress ip = null;
//        try {
//            // 列举
//            Enumeration<NetworkInterface> en_netInterface = NetworkInterface.getNetworkInterfaces();
//            while (en_netInterface.hasMoreElements()) {// 是否还有元素
//                NetworkInterface ni = (NetworkInterface) en_netInterface.nextElement();// 得到下一个元素
//                Enumeration<InetAddress> en_ip = ni.getInetAddresses();// 得到一个ip地址的列举
//                while (en_ip.hasMoreElements()) {
//                    ip = en_ip.nextElement();
//                    if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1)
//                        break;
//                    else
//                        ip = null;
//                }
//
//                if (ip != null) {
//                    break;
//                }
//            }
//        } catch (SocketException e) {
//
//            e.printStackTrace();
//        }
//        return ip;
//    }
//
//    /**
//     * 通过网络接口取
//     *
//     * @return
//     */
//    public static String getMac4() {
//        try {
//            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
//            for (NetworkInterface nif : all) {
//                if (!nif.getName().equalsIgnoreCase("wlan0"))
//                    continue;
//
//                byte[] macBytes = nif.getHardwareAddress();
//                if (macBytes == null) {
//                    return null;
//                }
//
//                StringBuilder res1 = new StringBuilder();
//                for (byte b : macBytes) {
//                    res1.append(String.format("%02X:", b));
//                }
//
//                if (res1.length() > 0) {
//                    res1.deleteCharAt(res1.length() - 1);
//                }
//                return res1.toString();
//            }
//        } catch (Exception ex) {
//            ex.printStackTrace();
//        }
//        return null;
//    }
//


//    private static final String readFileContent(String filePath) {
//        StringBuilder builder = new StringBuilder();
//        InputStream inputStream = null;
//        InputStreamReader reader = null;
//        try {
//            String[] args = {"/system/bin/cat", filePath};
//            ProcessBuilder cmd = new ProcessBuilder(args);
//            Process process = cmd.start();
//            inputStream = process.getInputStream();
//            reader = new InputStreamReader(inputStream, "utf-8");
//            char[] buffer = new char[24];
//            int lenght = -1;
//            while ((lenght = reader.read(buffer)) != -1) {
//                builder.append(buffer, 0, lenght);
//            }
//        } catch (UnsupportedEncodingException ex) {
//            WL.e(TAG, "getMaxCpuFreq ---> UnsupportedEncodingException");
//            builder.delete(0, builder.length());
//            builder.append("N/A");
//        } catch (IOException ex) {
//            WL.e(TAG, "getMaxCpuFreq ---> IOException");
//            builder.delete(0, builder.length());
//            builder.append("N/A");
//        } finally {
//            IoUtils.closeSilently(reader);
//            IoUtils.closeSilently(inputStream);
//        }
//        return builder.toString().trim();
//    }
}
